<template>
  <div class="order-container">
    <Header />
    
    <div class="main-content">
      <div class="order-wrapper">
        <h2 class="page-title">我的订单</h2>
        
        <!-- 订单状态筛选 -->
        <div class="order-filter">
          <el-radio-group v-model="statusFilter" @change="handleFilterChange">
            <el-radio-button :label="null">全部订单</el-radio-button>
            <el-radio-button :label="0">待付款</el-radio-button>
            <el-radio-button :label="1">待接单</el-radio-button>
            <el-radio-button :label="2">备餐中</el-radio-button>
            <el-radio-button :label="3">配送中</el-radio-button>
            <el-radio-button :label="4">已完成</el-radio-button>
            <el-radio-button :label="5">已取消</el-radio-button>
          </el-radio-group>
        </div>
        
        <!-- 订单列表 -->
        <div class="order-list" v-loading="loading">
          <!-- 空状态 -->
          <div class="empty-state" v-if="orders.length === 0 && !loading">
            <el-empty description="暂无订单记录" :image-size="200">
              <el-button type="primary" @click="goToMerchants">去下单</el-button>
            </el-empty>
          </div>
          
          <!-- 订单卡片列表 -->
          <div v-else>
            <el-card v-for="order in orders" :key="order.id" class="order-card">
              <div class="order-header">
                <div class="order-info">
                  <span class="order-time">下单时间：{{ formatDate(order.createTime) }}</span>
                  <span class="order-no">订单号：{{ order.orderNo }}</span>
                </div>
                <div class="order-status" :class="'status-' + order.status">
                  {{ getStatusText(order.status) }}
                </div>
              </div>
              
              <!-- <div class="merchant-info">
                <div class="merchant-name">{{ order.merchantName || '商家名称' }}</div>
              </div> -->
              
              <!-- 订单详情 -->
              <div class="order-items">
                <div class="item" v-for="item in order.orderDetails" :key="item.id">
                  <div class="item-image">
                    <img :src="item.foodImage" :alt="item.foodName" v-if="item.foodImage">
                    <div class="placeholder" v-else></div>
                  </div>
                  <div class="item-info">
                    <div class="item-name">{{ item.foodName }}</div>
                    <div class="item-price">¥{{ item.price }}</div>
                  </div>
                  <div class="item-quantity">x{{ item.quantity }}</div>
                </div>
              </div>
              
              <div class="order-footer">
                <div class="order-total">
                  <span>共{{ getTotalQuantity(order) }}件商品，合计：</span>
                  <span class="price">¥{{ order.totalPrice }}</span>
                </div>
                
                <div class="order-actions">
                  <!-- 根据订单状态显示不同按钮 -->
                  <!-- 待付款状态 -->
                  <template v-if="order.status === 0">
                    <el-button type="primary" size="small" @click="payOrder(order)">去支付</el-button>
                    <el-button size="small" @click="cancelOrder(order)">取消订单</el-button>
                  </template>
                  
                  <!-- 配送中状态 -->
                  <template v-if="order.status === 3">
                    <el-button type="primary" size="small" @click="completeOrder(order)">确认收货</el-button>
                  </template>
                  
                  <!-- 已完成状态 -->
                  <template v-if="order.status === 4 && !hasReviewed(order)">
                    <el-button type="primary" size="small" @click="reviewOrder(order)">评价订单</el-button>
                  </template>
                  
                  <!-- 查看详情按钮对所有状态都显示 -->
                  <el-button size="small" @click="viewOrderDetail(order)">查看详情</el-button>
                  
                  <!-- 已完成或已取消状态可以删除 -->
                  <el-button size="small" type="danger" v-if="order.status === 4 || order.status === 5" 
                             @click="deleteOrder(order)">删除订单</el-button>
                </div>
              </div>
            </el-card>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                :current-page.sync="currentPage"
                @current-change="handlePageChange">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 评价对话框 -->
    <el-dialog title="订单评价" :visible.sync="reviewDialogVisible" width="500px">
      <el-form :model="reviewForm" ref="reviewForm" :rules="reviewRules">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="reviewForm.rating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"></el-rate>
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input type="textarea" v-model="reviewForm.content" :rows="4" placeholder="请输入您的评价内容"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReview" :loading="submitting">提 交</el-button>
      </span>
    </el-dialog>
    
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import { mapGetters } from 'vuex'
import { getUserOrders, cancelOrder, completeOrder, deleteOrder } from '@/api/order'
import { addReview } from '@/api/review'

export default {
  name: 'Order',
  components: {
    Header,
    Footer
  },
  data() {
    return {
      // 订单列表
      orders: [],
      // 加载状态
      loading: false,
      // 状态筛选
      statusFilter: null,
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 评价对话框
      reviewDialogVisible: false,
      reviewForm: {
        orderId: null,
        merchantId: null,
        rating: 5,
        content: ''
      },
      reviewRules: {
        rating: [
          { required: true, message: '请给出评分', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评价内容', trigger: 'blur' },
          { min: 5, max: 200, message: '评价内容长度在5到200个字符之间', trigger: 'blur' }
        ]
      },
      submitting: false
    }
  },
  computed: {
    ...mapGetters(['currentUser'])
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    // 获取订单列表
    fetchOrders() {
      if (!this.currentUser) return
      
      this.loading = true
      
      getUserOrders(this.currentUser.id, this.currentPage, this.pageSize, this.statusFilter)
        .then(response => {
          if (response.code === 200) {
            this.orders = response.data
            this.total = response.total || 0
          } else {
            this.$message.error(response.message || '获取订单失败')
          }
        })
        .catch(error => {
          console.error('获取订单失败', error)
          this.$message.error('获取订单失败，请稍后再试')
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 状态筛选变化
    handleFilterChange() {
      this.currentPage = 1
      this.fetchOrders()
    },
    
    // 页码变化
    handlePageChange(page) {
      this.currentPage = page
      this.fetchOrders()
    },
    
    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待接单',
        2: '备餐中',
        3: '配送中',
        4: '已完成',
        5: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    
    // 计算订单总数量
    getTotalQuantity(order) {
      if (!order.orderDetails || order.orderDetails.length === 0) {
        return 0
      }
      return order.orderDetails.reduce((sum, item) => sum + item.quantity, 0)
    },
    
    // 跳转到详情页
    viewOrderDetail(order) {
      this.$router.push(`/orders/${order.id}`)
    },
    
    // 支付订单
    payOrder(order) {
      this.$router.push(`/orders/${order.id}?action=pay`)
    },
    
    // 取消订单
    cancelOrder(order) {
      this.$confirm('确定要取消该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const reason = '用户主动取消'
        cancelOrder(order.id, reason, this.currentUser.id)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('订单已取消')
              // 刷新订单列表
              this.fetchOrders()
            } else {
              this.$message.error(response.message || '取消订单失败')
            }
          })
          .catch(error => {
            console.error('取消订单失败', error)
            this.$message.error('取消订单失败，请稍后再试')
          })
      }).catch(() => {})
    },
    
    // 确认收货
    completeOrder(order) {
      this.$confirm('确认已收到商品吗?', '提示', {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        completeOrder(order.id, this.currentUser.id)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('确认收货成功')
              // 刷新订单列表
              this.fetchOrders()
            } else {
              this.$message.error(response.message || '确认收货失败')
            }
          })
          .catch(error => {
            console.error('确认收货失败', error)
            this.$message.error('确认收货失败，请稍后再试')
          })
      }).catch(() => {})
    },
    
    // 删除订单
    deleteOrder(order) {
      this.$confirm('确定要删除该订单吗? 删除后将无法恢复', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrder(order.id)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('订单已删除')
              // 刷新订单列表
              this.fetchOrders()
            } else {
              this.$message.error(response.message || '删除订单失败')
            }
          })
          .catch(error => {
            console.error('删除订单失败', error)
            this.$message.error('删除订单失败，请稍后再试')
          })
      }).catch(() => {})
    },
    
    // 评价订单
    reviewOrder(order) {
      this.reviewForm = {
        orderId: order.id,
        merchantId: order.merchantId,
        rating: 5,
        content: ''
      }
      this.reviewDialogVisible = true
    },
    
    // 提交评价
    submitReview() {
      this.$refs.reviewForm.validate(valid => {
        if (valid) {
          this.submitting = true
          
          // 添加用户ID
          const reviewData = {
            ...this.reviewForm,
            userId: this.currentUser.id
          }
          
          addReview(reviewData)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('评价提交成功')
                this.reviewDialogVisible = false
                // 刷新订单列表
                this.fetchOrders()
              } else {
                this.$message.error(response.message || '评价提交失败')
              }
            })
            .catch(error => {
              console.error('评价提交失败', error)
              this.$message.error('评价提交失败，请稍后再试')
            })
            .finally(() => {
              this.submitting = false
            })
        }
      })
    },
    
    // 检查是否已评价
    hasReviewed(order) {
      // 这里应该通过接口查询，简化处理
      return order.hasReviewed === true
    },
    
    // 跳转到商家列表
    goToMerchants() {
      this.$router.push('/merchants')
    }
  }
}
</script>

<style scoped>
.order-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.main-content {
  flex: 1;
  padding: 30px 0;
}

.order-wrapper {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.order-filter {
  margin-bottom: 20px;
}

.order-list {
  min-height: 400px;
}

.order-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.order-info {
  font-size: 14px;
  color: #666;
}

.order-no {
  margin-left: 20px;
}

.order-status {
  font-weight: bold;
}

.status-0 { color: #E6A23C; }
.status-1 { color: #409EFF; }
.status-2 { color: #409EFF; }
.status-3 { color: #409EFF; }
.status-4 { color: #67C23A; }
.status-5 { color: #909399; }

.merchant-info {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.merchant-name {
  font-size: 16px;
  font-weight: bold;
}

.order-items {
  padding: 15px 0;
}

.item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.item:last-child {
  margin-bottom: 0;
}

.item-image {
  width: 60px;
  height: 60px;
  overflow: hidden;
  margin-right: 15px;
  border-radius: 4px;
  background-color: #f0f0f0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-image .placeholder {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.item-price {
  color: #FF6B00;
  font-size: 14px;
}

.item-quantity {
  color: #999;
  margin-left: 20px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.order-total {
  font-size: 14px;
}

.order-total .price {
  color: #FF6B00;
  font-size: 18px;
  font-weight: bold;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  text-align: center;
  margin-top: 30px;
}

.empty-state {
  padding: 50px 0;
  text-align: center;
}
</style> 